import 'package:flutter/cupertino.dart';
import 'package:lib_bt/BleManager.dart';
import 'package:lib_bt/send/BleSendManager.dart';
import 'package:lib_bt/send/SendBean.dart';
import 'package:lib_util/ByteUtils.dart';
import 'package:ileddemo/code/ble/protocol/iledcolor/source/partition/PartitionSourceBean.dart';

import '../../AutoConnectUtil.dart';
import '../../SendProgressDialogUtil.dart';
import '../../base/LedBleBeanInterface.dart';
import '../BleBean.dart';
import '../send/ColorPackageImpl.dart';

class SourceSendUtil extends ChangeNotifier {
  //单例
  static SourceSendUtil? _instance;

  static SourceSendUtil get instance => _instance ??= SourceSendUtil._();

  SourceSendUtil._();

  int currentSourceId = 0;

  void sendSource(PartitionSourceBean sourceBean) async {
    currentSourceId = sourceBean.id;
    notifyListeners();
    var bleBeans = BleManager.instance.getConnectBleBeans();
    if (bleBeans.isEmpty) {
      return;
    }
    SendProgressDialogUtil.instance.showDialog();
    BleBean bleBean = BleBean(bean: AutoConnectUtil.instance.getLastConnectBleBean());
    var textData = await sourceBean.getSendData(bleBean);

    var package = ColorPackageImpl.createSimplePackage(
        [0x54, 0x06], textData.sublist(0, 4) + ByteUtils.int2Byte(textData.length)+[0,0,0]);

    List<SendBean> sendBeans = [];
    for (var bleBean in bleBeans) {
      SendBean sendBean = SendBean()
        ..address = bleBean.address
        ..addPackage(package);
      sendBean.addPackages(ColorPackageImpl.createPackage(textData, bleBean.mtu));
      sendBeans.add(sendBean);
    }
    BleSendManager.instance.send(sendBeans, onError: (msg, data) {
      print("发送失败");
      SendProgressDialogUtil.instance.dismissDialog();
    }, onSuccess: (msg, data) {
      print("发送成功");
      SendProgressDialogUtil.instance.dismissDialog();
    });
  }
}
